package com.shujia.hdfs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;

public class Demo1Hdfs {
    public static void main(String[] args) throws Exception {
        /**
         * java 操作hdfs
         *
         * fileSystem  hdfs文件系统在java代码里的抽象    操作hdfs的入口
         *
         */


        //hdfs 连接地址
        URI uri = new URI("hdfs://node1:9000");

        //hadoop 配置文件对象
        Configuration configuration = new Configuration();

        //文件操作对象
        FileSystem fileSystem = FileSystem.get(uri, configuration);

        //创建目录
        fileSystem.mkdirs(new Path("/java"));

        Path path = new Path("/java");
        //获取父级目录
        Path parent = path.getParent();



        //删除目录
        fileSystem.delete(new Path("/java"), true);

        //判断文件是否存在
        boolean exists = fileSystem.exists(new Path("/java"));
        System.out.println(exists);

        //判断是否是文件
        boolean isfile = fileSystem.isFile(new Path("/a.txt"));
        System.out.println(isfile);

        //判断是否是目录
        boolean directory = fileSystem.isDirectory(new Path("/java"));
        System.out.println(directory);


        //获取文件详细信息
        FileStatus[] fileStatuses = fileSystem.listStatus(new Path("/"));
        for (FileStatus fileStatus : fileStatuses) {
            System.out.println(fileStatus.getBlockSize() + "\t" + fileStatus.getPath());
            System.out.println(fileStatus.getLen());
        }


        //创建一个文件，返回一个字节输出流
        FSDataOutputStream fsDataOutputStream = fileSystem.create(new Path("/b.txt"), true);
        //FSDataOutputStream fsDataOutputStream = fileSystem.create(new Path("/b.txt"), (short) 1);

        //写数据
//        fsDataOutputStream.writeUTF("数加学院牛逼");
//        fsDataOutputStream.close();

        //将字节流转换成字符流
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fsDataOutputStream);
        BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

        bufferedWriter.write("数加学院");
        bufferedWriter.newLine();
        bufferedWriter.write("java");

        bufferedWriter.flush();
        bufferedWriter.close();


        /**
         * 读取hdfs数据
         *
         * 用什么流写的就用什么流读
         *
         */

        FSDataInputStream inputStream = fileSystem.open(new Path("/b.txt"));

        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }

        bufferedReader.close();

        //关闭连接
        fileSystem.close();


    }
}
